package com.zone.trigger.listener;

import com.alibaba.fastjson.JSONObject;
import com.zone.domain.common.factory.SimpleFactory;
import com.zone.domain.rebate.event.UserRebateEvent;
import com.zone.domain.rebate.model.valobj.BehaviorTypeEnum;
import com.zone.domain.rebate.model.valobj.RebateTypeEnum;
import com.zone.domain.rebate.service.settle.IUserBehaviorRebateSettle;
import com.zone.types.event.BaseMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author: zongzi
 * @description: 用户返利-消息消费端
 * @date: 2025/3/3
 */
@Slf4j
@Component
public class UserRebateConsumer {

    @RabbitListener(queuesToDeclare = @Queue(value = "${spring.rabbitmq.topic.user_rebate}"))
    public void consumer(BaseMessage<UserRebateEvent> message) {
        log.info("用户行为返利消息：message = {}", JSONObject.toJSONString(message));
        UserRebateEvent userRebateEvent = message.getData();
        BehaviorTypeEnum behaviorTypeEnum = BehaviorTypeEnum.valueOf(userRebateEvent.getBehaviorType());
        RebateTypeEnum rebateTypeEnum = RebateTypeEnum.valueOf(userRebateEvent.getRebateType());

        SimpleFactory<IUserBehaviorRebateSettle> userBehaviorRebateSettleFactory = new SimpleFactory<>(IUserBehaviorRebateSettle.class);
        String factoryName = String.format("%s_%s", behaviorTypeEnum.getCode(), rebateTypeEnum.getCode());
        IUserBehaviorRebateSettle settleHandler = userBehaviorRebateSettleFactory.newInstance(factoryName);
        if (Objects.isNull(settleHandler)) {
            log.info("未查询到用户返利消息处理器 behaviorTypeEnum = {}. rebateTypeEnum = {}", behaviorTypeEnum, rebateTypeEnum);
            return;
        }
        try {
            settleHandler.execute(userRebateEvent.getUserId(), userRebateEvent.getBehaviorType(), userRebateEvent.getRebateType(), userRebateEvent.getRebateConfig());
        } catch (Exception e) {
            log.error("返利结算处理器：{} 执行异常，执行参数：{}", settleHandler.getClass().getSimpleName(), JSONObject.toJSONString(userRebateEvent));
        }
    }
}
